/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.Js;
import com.jeeplus.modules.fee.entity.Receivable;
import com.jeeplus.modules.fee.service.JsService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.LoadJsService;
import com.jeeplus.modules.infor.service.RentJsService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.service.DetilJsService;

/**
 * 结算单收款总表Controller
 * @author 李超辉
 * @version 2018-09-29
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/detilJs")
public class DetilJsController extends BaseController {

	@Autowired
	private DetilJsService detilJsService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private LoadJsService loadJsService;
	@Autowired
	private RentJsService rentJsService;
	@Autowired
	private JsService jsService;
	
	@ModelAttribute
	public DetilJs get(@RequestParam(required=false) String id) {
		DetilJs entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = detilJsService.get(id);
		}
		if (entity == null){
			entity = new DetilJs();
		}
		return entity;
	}


	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(Date min, Date max, String pro) {
		jdbc.execute("delete from infor_detil_js");
		Calendar c = Calendar.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=min;
		Date mixx;
		Date maxx;
		if(min==null||max==null){
			return "false";
		}
		while (i.getTime()<max.getTime()) {
			mixx=i;
			DetilJs detilJs=new DetilJs();
			detilJs.setDate(i);
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			maxx=i;
			//仓租
			RentJs rentDetil=new RentJs();
			//装卸
			LoadJs loadDetil=new LoadJs();
			//运输
			Js receivable=new Js();
			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				rentDetil.setPro(pro);
				loadDetil.setPro(pro);
				receivable.setPro(pro);
			}else if(!UserUtils.getUseroffice().equals("总部")){
				rentDetil.setPro(UserUtils.getUseroffice());
				loadDetil.setPro(UserUtils.getUseroffice());
				receivable.setPro(pro);
			}
			//仓租
			rentDetil.setDate(mixx);
			List<RentJs> rens=rentJsService.findList(rentDetil);
			double czje=0.0;
			double czjs=0.0;
			double czwjs=0.0;
			for(RentJs r:rens){
				    czje+=Double.parseDouble(r.getKpje());
					czjs+=Double.parseDouble(r.getHx());
					czwjs+=Double.parseDouble(r.getWhx());

			}
			detilJs.setCzje(nf.format(czje).replaceAll(",",""));
			detilJs.setCzwsk(nf.format(czwjs).replaceAll(",",""));
			detilJs.setCzsk(nf.format(czjs).replaceAll(",",""));

			//装卸
			loadDetil.setDate(mixx);
			List<LoadJs> ls=loadJsService.findList(loadDetil);
			double zxys=0.0;
			double zxkp=0.0;
			double zxwkp=0.0;
			for(LoadJs l:ls){
				    zxys+=Double.parseDouble(l.getKpje());
					zxkp+=Double.parseDouble(l.getHx());
					zxwkp+=Double.parseDouble(l.getWhx());
			}

		    detilJs.setZxsk(nf.format(zxkp).replaceAll(",",""));
		    detilJs.setZxwsk(nf.format(zxwkp).replaceAll(",",""));
		    detilJs.setZxje(nf.format(zxys).replaceAll(",",""));

			//运输
			receivable.setMin(format.format(mixx));
			receivable.setMax(format.format(maxx));
			List<Js> res=jsService.findList(receivable);
			double ysys=0.0;
			double yskp=0.0;
			double yswkp=0.0;
			for(Js r:res){
				ysys+=Double.parseDouble(r.getKpje());
					yskp+=Double.parseDouble(r.getHxje());
					yswkp+=Double.parseDouble(r.getWhxje());

			}
			detilJs.setYssk(nf.format(yskp).replaceAll(",",""));
			detilJs.setYswsk(nf.format(yswkp).replaceAll(",",""));
			detilJs.setYsje(nf.format(ysys).replaceAll(",",""));
			double zys=ysys+czje+zxys;
			double zkp=yskp+czjs+zxkp;
			double zwkp=yswkp+czwjs+zxwkp;
			detilJs.setZje(nf.format(zys).replaceAll(",",""));
			detilJs.setZsk(nf.format(zkp).replaceAll(",",""));
			detilJs.setZwsk(nf.format(zwkp).replaceAll(",",""));
			detilJsService.save(detilJs);
		}
		return "success";
	}
	/**
	 * 结算单收款总表列表页面
	 */
	@RequiresPermissions("infor:detilJs:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/detilJsList";
	}
	
		/**
	 * 结算单收款总表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:detilJs:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(DetilJs detilJs, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<DetilJs> page = detilJsService.findPage(new Page<DetilJs>(request, response), detilJs); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑结算单收款总表表单页面
	 */
	@RequiresPermissions(value={"infor:detilJs:view","infor:detilJs:add","infor:detilJs:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(DetilJs detilJs, Model model) {
		model.addAttribute("detilJs", detilJs);
		return "modules/infor/detilJsForm";
	}

	/**
	 * 保存结算单收款总表
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:detilJs:add","infor:detilJs:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(DetilJs detilJs, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, detilJs)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		detilJsService.save(detilJs);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存结算单收款总表成功");
		return j;
	}
	
	/**
	 * 删除结算单收款总表
	 */
	@ResponseBody
	@RequiresPermissions("infor:detilJs:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(DetilJs detilJs, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		detilJsService.delete(detilJs);
		j.setMsg("删除结算单收款总表成功");
		return j;
	}
	
	/**
	 * 批量删除结算单收款总表
	 */
	@ResponseBody
	@RequiresPermissions("infor:detilJs:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			detilJsService.delete(detilJsService.get(id));
		}
		j.setMsg("删除结算单收款总表成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:detilJs:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(DetilJs detilJs, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "结算单收款总表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<DetilJs> page = detilJsService.findPage(new Page<DetilJs>(request, response, -1), detilJs);
    		new ExportExcel("结算单收款总表", DetilJs.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出结算单收款总表记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:detilJs:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<DetilJs> list = ei.getDataList(DetilJs.class);
			for (DetilJs detilJs : list){
				try{
					detilJsService.save(detilJs);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条结算单收款总表记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条结算单收款总表记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入结算单收款总表失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/detilJs/?repage";
    }
	
	/**
	 * 下载导入结算单收款总表数据模板
	 */
	@RequiresPermissions("infor:detilJs:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "结算单收款总表数据导入模板.xlsx";
    		List<DetilJs> list = Lists.newArrayList(); 
    		new ExportExcel("结算单收款总表数据", DetilJs.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/detilJs/?repage";
    }

}